const axios = require('axios')
const qs = require('qs')
const crypto = require('crypto')

const appKey = 'red.vUoI9uw7OAVuf2wY'

const appSecret = '0768e122d55e7be6131ed196d412ef65'

function sha256(input) {
    const hash = crypto.createHash('sha256')
    hash.update(input)
    return hash.digest('hex')
}

const bookApi = {
    async getAccessToken() {
        const timestamp = new Date().getTime() - 1000
        const nonce = Math.random() + ''
        const expires_in = timestamp + 24 * 60 * 60 * 1000
        const str =
            qs.stringify({
                appKey,
                nonce,
                timeStamp: timestamp + '',
            }) + appSecret

        const signature = sha256(str)

        const res = await axios({
            method: 'POST',
            url: 'https://edith.xiaohongshu.com/api/sns/v1/ext/access/token',
            data: {
                app_key: appKey,
                nonce,
                timestamp,
                signature,
                expires_in,
            },
            headers: {
                'Content-Type': 'application/json',
            },
        })
        console.log('接口响应：', res.data)
        const access_token = res.data.data.access_token
        //第二次加签

        const str2 =
            qs.stringify({
                appKey,
                nonce,
                timeStamp: timestamp + '',
            }) + access_token
        console.log(str2)
        const signature2 = sha256(str)
    },
}
bookApi.getAccessToken()
